package com.campus.controller;

import com.campus.domain.po.Class;
import com.campus.service.ClassService;
import com.campus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/class")
public class ClassController {

    @Autowired
    private ClassService classService;

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/create")
    public R createClass(@RequestBody Class classObj) {
        Class createdClass = classService.createClass(classObj);
        return R.success(createdClass);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/update")
    public R updateClass(@RequestBody Class classObj) {
        Class updatedClass = classService.updateClass(classObj);
        return updatedClass != null ? R.success(updatedClass) : R.error(500, "Failed to update class");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/addStudents/{classId}")
    public R addStudentsToClass(@PathVariable Integer classId, @RequestBody List<Integer> studentIds) {
        boolean success = classService.addStudentsToClass(classId, studentIds);
        return success ? R.success(200) : R.error(500, "Failed to add students to class");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/assignTeachers/{classId}")
    public R assignTeachersToClass(@PathVariable Integer classId, @RequestBody List<Integer> teacherIds) {
        boolean success = classService.assignTeachersToClass(classId, teacherIds);
        return success ? R.success(200) : R.error(500, "Failed to assign teachers to class");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/get/{id}")
    public R getClass(@PathVariable Integer id) {
        Class classObj = classService.getClassById(id);
        return classObj != null ? R.success(classObj) : R.error(500, "Class not found");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/list/{activityId}")
    public R getClassesByActivity(@PathVariable Integer activityId) {
        List<Class> classes = classService.getClassesByActivityId(activityId);
        return R.success(classes);
    }
}
